<?php

namespace App\Exceptions;

use App\Common\Libs\Json;
use App\Consts\ExceptionCode;

/**
 * 错误信息统一处理
 * Class Error
 * @package App\Exceptions
 */
class Error
{

    /** @var string default message */
    public static $message = 'INVALID REQUEST';

    /**
     * get error message
     * @param $code
     * @param string $default
     * @return mixed|string
     */
    public static function getMessage($code, $default = '')
    {
        try {
            $message = empty(ExceptionCode::$msgMap[$code]) ? $default : ExceptionCode::$msgMap[$code];
        } catch (\Exception $e) {
            $message = 'SYSTEM ERROR : ' . $e->getCode() . ' - ' . $e->getMessage();
        }

        return $message;
    }

    /**
     * app error throw
     * @param \Exception|mixed $exception
     * @param bool $extra
     * @param bool $isSend
     * @return mixed
     */
    public static function throw($exception, $extra = true, $isSend = true)
    {
        return appThrow($exception, $extra, $isSend);
    }

    /**
     * handle error
     * @param string $message
     * @param int $code
     * @param string $result
     * @param bool $interrupt 是否中断，默认 false
     * @return \Illuminate\Http\JsonResponse
     */
    public static function handle($message = '', $code = ExceptionCode::ILLEGAL_PARAMETER, $result = '', $interrupt = false)
    {
        $code = (int)$code;

        // 中断程序
        if ($interrupt) {
            if (is_array($result)) {
                $result = Json::encode($result);
            }
            $message = "#{$code} - " . $result;
            return app()->abort($code, $message);
        }


        if (empty($message)) {
            $message = self::getMessage($code);
        }

        // 线上屏蔽具体错误码
        // 结果为空屏蔽具体错误码（这是容错）
        if (isProd() || !$result) {
            $result = (object)[];
        }
        $result = !is_numeric($result) ?: $code . $result;

        $format = [
            'success' => $code == 200,
            'statusCode' => $code,
            'message' => $message,
            'result' => $result,
        ];
        return response()->json($format);
    }

}
